#include "GpsDataStruct.h"
#include "Logging.h"
#if defined(LINUX)
#include <pthread.h>
#endif

#if defined(LINUX)
static pQNode GpsDataQueue = NULL;
static pthread_mutex_t GpsDataMut;
#endif

#if defined(LINUX)
//创建队列，不是头结点
static pQNode CreateQueue()
{
	pQNode Q = (pQNode)malloc(sizeof(QNode));
	Q->front = Q->rear = NULL;
	return Q;
}

//为空返回0
static int IsEmpty(pQNode Q)
{
	if(NULL == Q)
		return -1;
	if (NULL == Q->front)
		return 0;
	else
		return -1;
}

static int AddQ(pQNode Q, void* X)
{
	if(NULL == Q || NULL == X)
		return -1;
	pNode temp = (pNode)malloc(sizeof(Node));
	temp->Data = X;
	temp->Next = NULL;
	if (!IsEmpty(Q))
		Q->front = Q->rear = temp;
	else
	{
		Q->rear->Next = temp;
		Q->rear = temp;
	}
	return 0;
}

static void* DeleteQ(pQNode Q)
{
	if(NULL == Q)
		return NULL;
	if (!IsEmpty(Q))
		return NULL;
	pNode temp = Q->front;
	void* X = temp->Data;
	if (Q->front == Q->rear)
		Q->front = Q->rear = NULL;
	else
		Q->front = Q->front->Next;
	free(temp);
	return X;
}

//获取队列长度
static int CountQ(pQNode Q)
{
	if(NULL == Q)
		return -1;
	if(!IsEmpty(Q))
		return 0;
	int count = 0;
	pNode temp = Q->front;
	while(NULL != temp)
	{
		count++;
		temp = temp->Next;
	}
	return count;
}

//初始化所有数据结构队列
int InitQueue()
{
	GpsDataQueue = CreateQueue();
	if (NULL == GpsDataQueue)
	{
		WriteFileLog(LERROR, "初始化数据结构队列失败 ！");
		return -1;
	}
	else
		return 0;
}

//向GpsData队列添加数据
int PushGpsData(GpsDataStruct* gds)
{
	if (NULL == GpsDataQueue)
	{
		//pthread_mutex_unlock(&GpsDataMut);
		WriteFileLog(LERROR, "队列添加数据失败, 队列不存在 ！");
		return -1;
	}
	pthread_mutex_trylock(&GpsDataMut);
	AddQ(GpsDataQueue, gds);
	pthread_mutex_unlock(&GpsDataMut);
	return 0;
}

//从GpsData队列取数据
GpsDataStruct* PopGpsData()
{
	if (NULL == GpsDataQueue || !IsEmpty(GpsDataQueue))
	{
		//pthread_mutex_unlock(&GpsDataMut);
		//WriteFileLog(LERROR, "队列取数据失败，队列为空或队列不存在 ！");
		return NULL;
	}
	pthread_mutex_trylock(&GpsDataMut);
	GpsDataStruct* ret = DeleteQ(GpsDataQueue);
	pthread_mutex_unlock(&GpsDataMut);
	return ret;
}

//查看GpsData队列是否有数据 有数据返回0
int HasGpsData()
{
	if (NULL == GpsDataQueue)
	{
		WriteFileLog(LERROR, "查看队列是否有数据失败 ！");
		return -1;
	}
	return !IsEmpty(GpsDataQueue);
}

//获取gpsdata队列中所有数据
//return:   取到的数据个数
int GetAllFromGpsdataQ(GpsDataStruct*** gdsArray)
{
	if(NULL == GpsDataQueue || HasGpsData())
	{
		//WriteFileLog(LERROR, "获取gpsdata队列中所有数据失败, 队列为空或队列不存在 ！");
		return -1;
	}
	int count = CountQ(GpsDataQueue);
	GpsDataStruct** retArray = (GpsDataStruct**)malloc(sizeof(GpsDataStruct*)*count);
	//pthread_mutex_trylock(&GpsDataMut);
	int i = 0;
	for(i;i<count;i++)
		retArray[i] = PopGpsData();
	//pthread_mutex_unlock(&GpsDataMut);
	*gdsArray = retArray;
	return count;
}

#endif
